package com.zhanghu.backendZray.listener;

import javax.servlet.ServletContext;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

/**
 * 统计在线用户数
 */
@WebListener
public class CountOnlineListener implements HttpSessionListener {

    // 会话创建时执行
    public void sessionCreated(HttpSessionEvent httpSessionEvent) {
        ServletContext context = httpSessionEvent.getSession().getServletContext();
        // 判断Context对象是否存在这个域，如果存在人数+1;如果不存在，那么就将属性设置到Context域中
        Integer num = (Integer) context.getAttribute("num");
        if (num == null) {
            context.setAttribute("num", 1);
        } else {
            num++;
            context.setAttribute("num", num);
        }
    }

    // 会话销毁时执行
    public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
        ServletContext context = httpSessionEvent.getSession().getServletContext();
        Integer num = (Integer) httpSessionEvent.getSession().getAttribute("num");
        if (num == null) {
            context.setAttribute("num", 1);
        } else {
            num--;
            context.setAttribute("num", num);
        }
    }

}